package com.base.service.impl;

import java.util.List;

import com.base.service.MenuService;
import com.common.bean.Menuinfo;
import com.common.util.AbstractManager;
import com.common.util.PagerModel;

public class MenuServiceImpl extends AbstractManager implements MenuService {

	public void addMenu(Menuinfo menuinfo) {
		if(menuinfo == null){
			throw new RuntimeException("no instance will be save.");
		}
		
		String hql = "select nvl(max(menuid),0) from Menuinfo ";
		long count = -1l;
		count = (Long)this.getHibernateTemplate().find(hql).get(0);
		count += 1l;
		
		long menuid = count ;
		menuinfo.setMenuid(menuid);
		menuinfo.setTarget("main");
		this.getHibernateTemplate().save(menuinfo);
	}
	
	public void addMenu(Menuinfo menuinfo,long menupid) {
		String hql = "select nvl(max(menuid),0) from Menuinfo ";
		long count = -1l;
		count = (Long)this.getHibernateTemplate().find(hql).get(0);
		count += 1l;
		
		long menuid = count;
		menuinfo.setMenuid(menuid);
		menuinfo.setMenupid(menupid);
		menuinfo.setTarget("main");
		this.getHibernateTemplate().save(menuinfo);
	}

	public void removeMenu(Long menuid) {
		List<Menuinfo> menulist = findChildMenuinfo(menuid);
		if(menulist != null && menulist.size() > 0 ) {
			throw new RuntimeException("含有下级菜单，不能删除！");
		}
		
		Menuinfo menuinfo = (Menuinfo) this.getHibernateTemplate().get(Menuinfo.class, menuid);
		
		if(menuinfo != null)
		this.getHibernateTemplate().delete(menuinfo);
	}

	@SuppressWarnings("unchecked")
	public List<Menuinfo> findAllMenuinfo() {
		String hql = "from Menuinfo  order by menuid ";
		return (List<Menuinfo>)this.getHibernateTemplate().find(hql);
	}

	public Menuinfo findMenuinfo(Long menuid) {
		return (Menuinfo) this.getHibernateTemplate().load(Menuinfo.class, menuid);
	}

	public void updateMenuinfo(Menuinfo menuinfo) {
		if(menuinfo != null & menuinfo.getMenuid() != -1){
			Menuinfo menu = this.findMenuinfo(menuinfo.getMenuid());
			if(menu == null) {
				throw new RuntimeException("没有找到菜单！");
			}
			
			menu.setMenuname(menuinfo.getMenuname());
			menu.setUrl(menuinfo.getUrl());
			
			this.getHibernateTemplate().saveOrUpdate(menu);
		}
	}

	public PagerModel findMenuinfo( int offset , int pagesize) {
		String hql = "from Menuinfo order by menuid ";
		return searchPaginated(hql ,offset,pagesize);
	}
	
	@SuppressWarnings("unchecked")
	public List<Menuinfo> findChildMenuinfo(long menupid) {
		String hql = "from Menuinfo menu where menu.menupid = ? order by menu.menuid ";
		return (List<Menuinfo>)this.getHibernateTemplate().find(hql,menupid);
	}

	public PagerModel findMenuinfo(long menupid, int offset, int pagesize) {
		String hql = "from Menuinfo menu where menu.menupid = ? order by menu.menuid ";
		return searchPaginated(hql,menupid,offset,pagesize);
	}
}
